home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1993 July / InfoMagic USENET CD-ROM July 1993.ISO / sources / unix / volume23 / flex2.3 / part02 < prev    next >
Encoding:
Internet Message Format  |  1990-10-10  |  54.3 KB

  1. Subject:  v23i038:  Flex, a fast lex replacement, Part02/10
  2. Newsgroups: comp.sources.unix
  3. Approved: rsalz@uunet.UU.NET
  4. X-Checksum-Snefru: 80b93637 ffdf31b4 21b5808a de7dfc4c
  5.  
  6. Submitted-by: Vern Paxson <vern@cs.cornell.edu>
  7. Posting-number: Volume 23, Issue 38
  8. Archive-name: flex2.3/part02
  9.  
  10. #! /bin/sh
  11. # This is a shell archive.  Remove anything before this line, then feed it
  12. # into a shell via "sh file" or similar.  To overwrite existing files,
  13. # type "sh file -c".
  14. # The tool that generated this appeared in the comp.sources.unix newsgroup;
  15. # send mail to comp-sources-unix@uunet.uu.net if you want that tool.
  16. # Contents:  COPYING flexdoc.1.01
  17. # Wrapped by rsalz@litchi.bbn.com on Wed Oct 10 13:23:58 1990
  18. PATH=/bin:/usr/bin:/usr/ucb ; export PATH
  19. echo If this archive is complete, you will see the following message:
  20. echo '          "shar: End of archive 2 (of 10)."'
  21. if test -f 'COPYING' -a "${1}" != "-c" ; then 
  22.   echo shar: Will not clobber existing file \"'COPYING'\"
  23. else
  24.   echo shar: Extracting \"'COPYING'\" \(1802 characters\)
  25.   sed "s/^X//" >'COPYING' <<'END_OF_FILE'
  26. XFlex carries the copyright used for BSD software, slightly modified
  27. Xbecause it originated at the Lawrence Berkeley (not Livermore!) Laboratory,
  28. Xwhich operates under a contract with the Department of Energy:
  29. X
  30. X    Copyright (c) 1990 The Regents of the University of California.
  31. X    All rights reserved.
  32. X
  33. X    This code is derived from software contributed to Berkeley by
  34. X    Vern Paxson.
  35. X
  36. X    The United States Government has rights in this work pursuant
  37. X    to contract no. DE-AC03-76SF00098 between the United States
  38. X    Department of Energy and the University of California.
  39. X
  40. X    Redistribution and use in source and binary forms are permitted
  41. X    provided that: (1) source distributions retain this entire
  42. X    copyright notice and comment, and (2) distributions including
  43. X    binaries display the following acknowledgement:  ``This product
  44. X    includes software developed by the University of California,
  45. X    Berkeley and its contributors'' in the documentation or other
  46. X    materials provided with the distribution and in all advertising
  47. X    materials mentioning features or use of this software.  Neither the
  48. X    name of the University nor the names of its contributors may be
  49. X    used to endorse or promote products derived from this software
  50. X    without specific prior written permission.
  51. X
  52. X    THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
  53. X    IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
  54. X    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  55. X    PURPOSE.
  56. X
  57. XThis basically says "do whatever you please with this software except
  58. Xremove this notice or take advantage of the University's (or the flex
  59. Xauthors') name".
  60. X
  61. XNote that the "flex.skel" scanner skeleton carries no copyright notice.
  62. XYou are free to do whatever you please with scanners generated using flex;
  63. Xfor them, you are not even bound by the above copyright.
  64. END_OF_FILE
  65.   if test 1802 -ne `wc -c <'COPYING'`; then
  66.     echo shar: \"'COPYING'\" unpacked with wrong size!
  67.   fi
  68.   # end of 'COPYING'
  69. fi
  70. if test -f 'flexdoc.1.01' -a "${1}" != "-c" ; then 
  71.   echo shar: Will not clobber existing file \"'flexdoc.1.01'\"
  72. else
  73.   echo shar: Extracting \"'flexdoc.1.01'\" \(49839 characters\)
  74.   sed "s/^X//" >'flexdoc.1.01' <<'END_OF_FILE'
  75. X.TH FLEX 1 "26 May 1990" "Version 2.3"
  76. X.SH NAME
  77. Xflex - fast lexical analyzer generator
  78. X.SH SYNOPSIS
  79. X.B flex
  80. X.B [-bcdfinpstvFILT8 -C[efmF] -Sskeleton]
  81. X.I [filename ...]
  82. X.SH DESCRIPTION
  83. X.I flex
  84. Xis a tool for generating
  85. X.I scanners:
  86. Xprograms which recognized lexical patterns in text.
  87. X.I flex
  88. Xreads
  89. Xthe given input files, or its standard input if no file names are given,
  90. Xfor a description of a scanner to generate.  The description is in
  91. Xthe form of pairs
  92. Xof regular expressions and C code, called
  93. X.I rules.  flex
  94. Xgenerates as output a C source file,
  95. X.B lex.yy.c,
  96. Xwhich defines a routine
  97. X.B yylex().
  98. XThis file is compiled and linked with the
  99. X.B -lfl
  100. Xlibrary to produce an executable.  When the executable is run,
  101. Xit analyzes its input for occurrences
  102. Xof the regular expressions.  Whenever it finds one, it executes
  103. Xthe corresponding C code.
  104. X.SH SOME SIMPLE EXAMPLES
  105. X.LP
  106. XFirst some simple examples to get the flavor of how one uses
  107. X.I flex.
  108. XThe following
  109. X.I flex
  110. Xinput specifies a scanner which whenever it encounters the string
  111. X"username" will replace it with the user's login name:
  112. X.nf
  113. X
  114. X    %%
  115. X    username    printf( "%s", getlogin() );
  116. X
  117. X.fi
  118. XBy default, any text not matched by a
  119. X.I flex
  120. Xscanner
  121. Xis copied to the output, so the net effect of this scanner is
  122. Xto copy its input file to its output with each occurrence
  123. Xof "username" expanded.
  124. XIn this input, there is just one rule.  "username" is the
  125. X.I pattern
  126. Xand the "printf" is the
  127. X.I action.
  128. XThe "%%" marks the beginning of the rules.
  129. X.LP
  130. XHere's another simple example:
  131. X.nf
  132. X
  133. X        int num_lines = 0, num_chars = 0;
  134. X
  135. X    %%
  136. X    \\n    ++num_lines; ++num_chars;
  137. X    .     ++num_chars;
  138. X
  139. X    %%
  140. X    main()
  141. X        {
  142. X        yylex();
  143. X        printf( "# of lines = %d, # of chars = %d\\n",
  144. X                num_lines, num_chars );
  145. X        }
  146. X
  147. X.fi
  148. XThis scanner counts the number of characters and the number
  149. Xof lines in its input (it produces no output other than the
  150. Xfinal report on the counts).  The first line
  151. Xdeclares two globals, "num_lines" and "num_chars", which are accessible
  152. Xboth inside
  153. X.B yylex()
  154. Xand in the
  155. X.B main()
  156. Xroutine declared after the second "%%".  There are two rules, one
  157. Xwhich matches a newline ("\\n") and increments both the line count and
  158. Xthe character count, and one which matches any character other than
  159. Xa newline (indicated by the "." regular expression).
  160. X.LP
  161. XA somewhat more complicated example:
  162. X.nf
  163. X
  164. X    /* scanner for a toy Pascal-like language */
  165. X
  166. X    %{
  167. X    /* need this for the call to atof() below */
  168. X    #include <math.h>
  169. X    %}
  170. X
  171. X    DIGIT    [0-9]
  172. X    ID       [a-z][a-z0-9]*
  173. X
  174. X    %%
  175. X
  176. X    {DIGIT}+    {
  177. X                printf( "An integer: %s (%d)\\n", yytext,
  178. X                        atoi( yytext ) );
  179. X                }
  180. X
  181. X    {DIGIT}+"."{DIGIT}*        {
  182. X                printf( "A float: %s (%g)\\n", yytext,
  183. X                        atof( yytext ) );
  184. X                }
  185. X
  186. X    if|then|begin|end|procedure|function        {
  187. X                printf( "A keyword: %s\\n", yytext );
  188. X                }
  189. X
  190. X    {ID}        printf( "An identifier: %s\\n", yytext );
  191. X
  192. X    "+"|"-"|"*"|"/"   printf( "An operator: %s\\n", yytext );
  193. X
  194. X    "{"[^}\\n]*"}"     /* eat up one-line comments */
  195. X
  196. X    [ \\t\\n]+          /* eat up whitespace */
  197. X
  198. X    .           printf( "Unrecognized character: %s\\n", yytext );
  199. X
  200. X    %%
  201. X
  202. X    main( argc, argv )
  203. X    int argc;
  204. X    char **argv;
  205. X        {
  206. X        ++argv, --argc;  /* skip over program name */
  207. X        if ( argc > 0 )
  208. X                yyin = fopen( argv[0], "r" );
  209. X        else
  210. X                yyin = stdin;
  211. X        
  212. X        yylex();
  213. X        }
  214. X
  215. X.fi
  216. XThis is the beginnings of a simple scanner for a language like
  217. XPascal.  It identifies different types of
  218. X.I tokens
  219. Xand reports on what it has seen.
  220. X.LP
  221. XThe details of this example will be explained in the following
  222. Xsections.
  223. X.SH FORMAT OF THE INPUT FILE
  224. XThe
  225. X.I flex
  226. Xinput file consists of three sections, separated by a line with just
  227. X.B %%
  228. Xin it:
  229. X.nf
  230. X
  231. X    definitions
  232. X    %%
  233. X    rules
  234. X    %%
  235. X    user code
  236. X
  237. X.fi
  238. XThe
  239. X.I definitions
  240. Xsection contains declarations of simple
  241. X.I name
  242. Xdefinitions to simplify the scanner specification, and declarations of
  243. X.I start conditions,
  244. Xwhich are explained in a later section.
  245. X.LP
  246. XName definitions have the form:
  247. X.nf
  248. X
  249. X    name definition
  250. X
  251. X.fi
  252. XThe "name" is a word beginning with a letter or an underscore ('_')
  253. Xfollowed by zero or more letters, digits, '_', or '-' (dash).
  254. XThe definition is taken to begin at the first non-white-space character
  255. Xfollowing the name and continuing to the end of the line.
  256. XThe definition can subsequently be referred to using "{name}", which
  257. Xwill expand to "(definition)".  For example,
  258. X.nf
  259. X
  260. X    DIGIT    [0-9]
  261. X    ID       [a-z][a-z0-9]*
  262. X
  263. X.fi
  264. Xdefines "DIGIT" to be a regular expression which matches a
  265. Xsingle digit, and
  266. X"ID" to be a regular expression which matches a letter
  267. Xfollowed by zero-or-more letters-or-digits.
  268. XA subsequent reference to
  269. X.nf
  270. X
  271. X    {DIGIT}+"."{DIGIT}*
  272. X
  273. X.fi
  274. Xis identical to
  275. X.nf
  276. X
  277. X    ([0-9])+"."([0-9])*
  278. X
  279. X.fi
  280. Xand matches one-or-more digits followed by a '.' followed
  281. Xby zero-or-more digits.
  282. X.LP
  283. XThe
  284. X.I rules
  285. Xsection of the
  286. X.I flex
  287. Xinput contains a series of rules of the form:
  288. X.nf
  289. X
  290. X    pattern   action
  291. X
  292. X.fi
  293. Xwhere the pattern must be unindented and the action must begin
  294. Xon the same line.
  295. X.LP
  296. XSee below for a further description of patterns and actions.
  297. X.LP
  298. XFinally, the user code section is simply copied to
  299. X.B lex.yy.c
  300. Xverbatim.
  301. XIt is used for companion routines which call or are called
  302. Xby the scanner.  The presence of this section is optional;
  303. Xif it is missing, the second
  304. X.B %%
  305. Xin the input file may be skipped, too.
  306. X.LP
  307. XIn the definitions and rules sections, any
  308. X.I indented
  309. Xtext or text enclosed in
  310. X.B %{
  311. Xand
  312. X.B %}
  313. Xis copied verbatim to the output (with the %{}'s removed).
  314. XThe %{}'s must appear unindented on lines by themselves.
  315. X.LP
  316. XIn the rules section,
  317. Xany indented or %{} text appearing before the
  318. Xfirst rule may be used to declare variables
  319. Xwhich are local to the scanning routine and (after the declarations)
  320. Xcode which is to be executed whenever the scanning routine is entered.
  321. XOther indented or %{} text in the rule section is still copied to the output,
  322. Xbut its meaning is not well-defined and it may well cause compile-time
  323. Xerrors (this feature is present for
  324. X.I POSIX
  325. Xcompliance; see below for other such features).
  326. X.LP
  327. XIn the definitions section, an unindented comment (i.e., a line
  328. Xbeginning with "/*") is also copied verbatim to the output up
  329. Xto the next "*/".  Also, any line in the definitions section
  330. Xbeginning with '#' is ignored, though this style of comment is
  331. Xdeprecated and may go away in the future.
  332. X.SH PATTERNS
  333. XThe patterns in the input are written using an extended set of regular
  334. Xexpressions.  These are:
  335. X.nf
  336. X
  337. X    x          match the character 'x'
  338. X    .          any character except newline
  339. X    [xyz]      a "character class"; in this case, the pattern
  340. X                 matches either an 'x', a 'y', or a 'z'
  341. X    [abj-oZ]   a "character class" with a range in it; matches
  342. X                 an 'a', a 'b', any letter from 'j' through 'o',
  343. X                 or a 'Z'
  344. X    [^A-Z]     a "negated character class", i.e., any character
  345. X                 but those in the class.  In this case, any
  346. X                 character EXCEPT an uppercase letter.
  347. X    [^A-Z\\n]   any character EXCEPT an uppercase letter or
  348. X                 a newline
  349. X    r*         zero or more r's, where r is any regular expression
  350. X    r+         one or more r's
  351. X    r?         zero or one r's (that is, "an optional r")
  352. X    r{2,5}     anywhere from two to five r's
  353. X    r{2,}      two or more r's
  354. X    r{4}       exactly 4 r's
  355. X    {name}     the expansion of the "name" definition
  356. X               (see above)
  357. X    "[xyz]\\"foo"
  358. X               the literal string: [xyz]"foo
  359. X    \\X         if X is an 'a', 'b', 'f', 'n', 'r', 't', or 'v',
  360. X                 then the ANSI-C interpretation of \\x.
  361. X                 Otherwise, a literal 'X' (used to escape
  362. X                 operators such as '*')
  363. X    \\123       the character with octal value 123
  364. X    \\x2a       the character with hexadecimal value 2a
  365. X    (r)        match an r; parentheses are used to override
  366. X                 precedence (see below)
  367. X
  368. X
  369. X    rs         the regular expression r followed by the
  370. X                 regular expression s; called "concatenation"
  371. X
  372. X
  373. X    r|s        either an r or an s
  374. X
  375. X
  376. X    r/s        an r but only if it is followed by an s.  The
  377. X                 s is not part of the matched text.  This type
  378. X                 of pattern is called as "trailing context".
  379. X    ^r         an r, but only at the beginning of a line
  380. X    r$         an r, but only at the end of a line.  Equivalent
  381. X                 to "r/\\n".
  382. X
  383. X
  384. X    <s>r       an r, but only in start condition s (see
  385. X               below for discussion of start conditions)
  386. X    <s1,s2,s3>r
  387. X               same, but in any of start conditions s1,
  388. X               s2, or s3
  389. X
  390. X
  391. X    <<EOF>>    an end-of-file
  392. X    <s1,s2><<EOF>>
  393. X               an end-of-file when in start condition s1 or s2
  394. X
  395. X.fi
  396. XThe regular expressions listed above are grouped according to
  397. Xprecedence, from highest precedence at the top to lowest at the bottom.
  398. XThose grouped together have equal precedence.  For example,
  399. X.nf
  400. X
  401. X    foo|bar*
  402. X
  403. X.fi
  404. Xis the same as
  405. X.nf
  406. X
  407. X    (foo)|(ba(r*))
  408. X
  409. X.fi
  410. Xsince the '*' operator has higher precedence than concatenation,
  411. Xand concatenation higher than alternation ('|').  This pattern
  412. Xtherefore matches
  413. X.I either
  414. Xthe string "foo"
  415. X.I or
  416. Xthe string "ba" followed by zero-or-more r's.
  417. XTo match "foo" or zero-or-more "bar"'s, use:
  418. X.nf
  419. X
  420. X    foo|(bar)*
  421. X
  422. X.fi
  423. Xand to match zero-or-more "foo"'s-or-"bar"'s:
  424. X.nf
  425. X
  426. X    (foo|bar)*
  427. X
  428. X.fi
  429. X.LP
  430. XSome notes on patterns:
  431. X.IP -
  432. XA negated character class such as the example "[^A-Z]"
  433. Xabove
  434. X.I will match a newline
  435. Xunless "\\n" (or an equivalent escape sequence) is one of the
  436. Xcharacters explicitly present in the negated character class
  437. X(e.g., "[^A-Z\\n]").  This is unlike how many other regular
  438. Xexpression tools treat negated character classes, but unfortunately
  439. Xthe inconsistency is historically entrenched.
  440. XMatching newlines means that a pattern like [^"]* can match an entire
  441. Xinput (overflowing the scanner's input buffer) unless there's another
  442. Xquote in the input.
  443. X.IP -
  444. XA rule can have at most one instance of trailing context (the '/' operator
  445. Xor the '$' operator).  The start condition, '^', and "<<EOF>>" patterns
  446. Xcan only occur at the beginning of a pattern, and, as well as with '/' and '$',
  447. Xcannot be grouped inside parentheses.  A '^' which does not occur at
  448. Xthe beginning of a rule or a '$' which does not occur at the end of
  449. Xa rule loses its special properties and is treated as a normal character.
  450. X.IP
  451. XThe following are illegal:
  452. X.nf
  453. X
  454. X    foo/bar$
  455. X    <sc1>foo<sc2>bar
  456. X
  457. X.fi
  458. XNote that the first of these, can be written "foo/bar\\n".
  459. X.IP
  460. XThe following will result in '$' or '^' being treated as a normal character:
  461. X.nf
  462. X
  463. X    foo|(bar$)
  464. X    foo|^bar
  465. X
  466. X.fi
  467. XIf what's wanted is a "foo" or a bar-followed-by-a-newline, the following
  468. Xcould be used (the special '|' action is explained below):
  469. X.nf
  470. X
  471. X    foo      |
  472. X    bar$     /* action goes here */
  473. X
  474. X.fi
  475. XA similar trick will work for matching a foo or a
  476. Xbar-at-the-beginning-of-a-line.
  477. X.SH HOW THE INPUT IS MATCHED
  478. XWhen the generated scanner is run, it analyzes its input looking
  479. Xfor strings which match any of its patterns.  If it finds more than
  480. Xone match, it takes the one matching the most text (for trailing
  481. Xcontext rules, this includes the length of the trailing part, even
  482. Xthough it will then be returned to the input).  If it finds two
  483. Xor more matches of the same length, the
  484. Xrule listed first in the
  485. X.I flex
  486. Xinput file is chosen.
  487. X.LP
  488. XOnce the match is determined, the text corresponding to the match
  489. X(called the
  490. X.I token)
  491. Xis made available in the global character pointer
  492. X.B yytext,
  493. Xand its length in the global integer
  494. X.B yyleng.
  495. XThe
  496. X.I action
  497. Xcorresponding to the matched pattern is then executed (a more
  498. Xdetailed description of actions follows), and then the remaining
  499. Xinput is scanned for another match.
  500. X.LP
  501. XIf no match is found, then the
  502. X.I default rule
  503. Xis executed: the next character in the input is considered matched and
  504. Xcopied to the standard output.  Thus, the simplest legal
  505. X.I flex
  506. Xinput is:
  507. X.nf
  508. X
  509. X    %%
  510. X
  511. X.fi
  512. Xwhich generates a scanner that simply copies its input (one character
  513. Xat a time) to its output.
  514. X.SH ACTIONS
  515. XEach pattern in a rule has a corresponding action, which can be any
  516. Xarbitrary C statement.  The pattern ends at the first non-escaped
  517. Xwhitespace character; the remainder of the line is its action.  If the
  518. Xaction is empty, then when the pattern is matched the input token
  519. Xis simply discarded.  For example, here is the specification for a program
  520. Xwhich deletes all occurrences of "zap me" from its input:
  521. X.nf
  522. X
  523. X    %%
  524. X    "zap me"
  525. X
  526. X.fi
  527. X(It will copy all other characters in the input to the output since
  528. Xthey will be matched by the default rule.)
  529. X.LP
  530. XHere is a program which compresses multiple blanks and tabs down to
  531. Xa single blank, and throws away whitespace found at the end of a line:
  532. X.nf
  533. X
  534. X    %%
  535. X    [ \\t]+        putchar( ' ' );
  536. X    [ \\t]+$       /* ignore this token */
  537. X
  538. X.fi
  539. X.LP
  540. XIf the action contains a '{', then the action spans till the balancing '}'
  541. Xis found, and the action may cross multiple lines.
  542. X.I flex 
  543. Xknows about C strings and comments and won't be fooled by braces found
  544. Xwithin them, but also allows actions to begin with
  545. X.B %{
  546. Xand will consider the action to be all the text up to the next
  547. X.B %}
  548. X(regardless of ordinary braces inside the action).
  549. X.LP
  550. XAn action consisting solely of a vertical bar ('|') means "same as
  551. Xthe action for the next rule."  See below for an illustration.
  552. X.LP
  553. XActions can include arbitrary C code, including
  554. X.B return
  555. Xstatements to return a value to whatever routine called
  556. X.B yylex().
  557. XEach time
  558. X.B yylex()
  559. Xis called it continues processing tokens from where it last left
  560. Xoff until it either reaches
  561. Xthe end of the file or executes a return.  Once it reaches an end-of-file,
  562. Xhowever, then any subsequent call to
  563. X.B yylex()
  564. Xwill simply immediately return, unless
  565. X.B yyrestart()
  566. Xis first called (see below).
  567. X.LP
  568. XActions are not allowed to modify yytext or yyleng.
  569. X.LP
  570. XThere are a number of special directives which can be included within
  571. Xan action:
  572. X.IP -
  573. X.B ECHO
  574. Xcopies yytext to the scanner's output.
  575. X.IP -
  576. X.B BEGIN
  577. Xfollowed by the name of a start condition places the scanner in the
  578. Xcorresponding start condition (see below).
  579. X.IP -
  580. X.B REJECT
  581. Xdirects the scanner to proceed on to the "second best" rule which matched the
  582. Xinput (or a prefix of the input).  The rule is chosen as described
  583. Xabove in "How the Input is Matched", and
  584. X.B yytext
  585. Xand
  586. X.B yyleng
  587. Xset up appropriately.
  588. XIt may either be one which matched as much text
  589. Xas the originally chosen rule but came later in the
  590. X.I flex
  591. Xinput file, or one which matched less text.
  592. XFor example, the following will both count the
  593. Xwords in the input and call the routine special() whenever "frob" is seen:
  594. X.nf
  595. X
  596. X            int word_count = 0;
  597. X    %%
  598. X
  599. X    frob        special(); REJECT;
  600. X    [^ \\t\\n]+   ++word_count;
  601. X
  602. X.fi
  603. XWithout the
  604. X.B REJECT,
  605. Xany "frob"'s in the input would not be counted as words, since the
  606. Xscanner normally executes only one action per token.
  607. XMultiple
  608. X.B REJECT's
  609. Xare allowed, each one finding the next best choice to the currently
  610. Xactive rule.  For example, when the following scanner scans the token
  611. X"abcd", it will write "abcdabcaba" to the output:
  612. X.nf
  613. X
  614. X    %%
  615. X    a        |
  616. X    ab       |
  617. X    abc      |
  618. X    abcd     ECHO; REJECT;
  619. X    .|\\n     /* eat up any unmatched character */
  620. X
  621. X.fi
  622. X(The first three rules share the fourth's action since they use
  623. Xthe special '|' action.)
  624. X.B REJECT
  625. Xis a particularly expensive feature in terms scanner performance;
  626. Xif it is used in
  627. X.I any
  628. Xof the scanner's actions it will slow down
  629. X.I all
  630. Xof the scanner's matching.  Furthermore,
  631. X.B REJECT
  632. Xcannot be used with the
  633. X.I -f
  634. Xor
  635. X.I -F
  636. Xoptions (see below).
  637. X.IP
  638. XNote also that unlike the other special actions,
  639. X.B REJECT
  640. Xis a
  641. X.I branch;
  642. Xcode immediately following it in the action will
  643. X.I not
  644. Xbe executed.
  645. X.IP -
  646. X.B yymore()
  647. Xtells the scanner that the next time it matches a rule, the corresponding
  648. Xtoken should be
  649. X.I appended
  650. Xonto the current value of
  651. X.B yytext
  652. Xrather than replacing it.  For example, given the input "mega-kludge"
  653. Xthe following will write "mega-mega-kludge" to the output:
  654. X.nf
  655. X
  656. X    %%
  657. X    mega-    ECHO; yymore();
  658. X    kludge   ECHO;
  659. X
  660. X.fi
  661. XFirst "mega-" is matched and echoed to the output.  Then "kludge"
  662. Xis matched, but the previous "mega-" is still hanging around at the
  663. Xbeginning of
  664. X.B yytext
  665. Xso the
  666. X.B ECHO
  667. Xfor the "kludge" rule will actually write "mega-kludge".
  668. XThe presence of
  669. X.B yymore()
  670. Xin the scanner's action entails a minor performance penalty in the
  671. Xscanner's matching speed.
  672. X.IP -
  673. X.B yyless(n)
  674. Xreturns all but the first
  675. X.I n
  676. Xcharacters of the current token back to the input stream, where they
  677. Xwill be rescanned when the scanner looks for the next match.
  678. X.B yytext
  679. Xand
  680. X.B yyleng
  681. Xare adjusted appropriately (e.g.,
  682. X.B yyleng
  683. Xwill now be equal to
  684. X.I n
  685. X).  For example, on the input "foobar" the following will write out
  686. X"foobarbar":
  687. X.nf
  688. X
  689. X    %%
  690. X    foobar    ECHO; yyless(3);
  691. X    [a-z]+    ECHO;
  692. X
  693. X.fi
  694. XAn argument of 0 to
  695. X.B yyless
  696. Xwill cause the entire current input string to be scanned again.  Unless you've
  697. Xchanged how the scanner will subsequently process its input (using
  698. X.B BEGIN,
  699. Xfor example), this will result in an endless loop.
  700. X.IP -
  701. X.B unput(c)
  702. Xputs the character
  703. X.I c
  704. Xback onto the input stream.  It will be the next character scanned.
  705. XThe following action will take the current token and cause it
  706. Xto be rescanned enclosed in parentheses.
  707. X.nf
  708. X
  709. X    {
  710. X    int i;
  711. X    unput( ')' );
  712. X    for ( i = yyleng - 1; i >= 0; --i )
  713. X        unput( yytext[i] );
  714. X    unput( '(' );
  715. X    }
  716. X
  717. X.fi
  718. XNote that since each
  719. X.B unput()
  720. Xputs the given character back at the
  721. X.I beginning
  722. Xof the input stream, pushing back strings must be done back-to-front.
  723. X.IP -
  724. X.B input()
  725. Xreads the next character from the input stream.  For example,
  726. Xthe following is one way to eat up C comments:
  727. X.nf
  728. X
  729. X    %%
  730. X    "/*"        {
  731. X                register int c;
  732. X
  733. X                for ( ; ; )
  734. X                    {
  735. X                    while ( (c = input()) != '*' &&
  736. X                            c != EOF )
  737. X                        ;    /* eat up text of comment */
  738. X
  739. X                    if ( c == '*' )
  740. X                        {
  741. X                        while ( (c = input()) == '*' )
  742. X                            ;
  743. X                        if ( c == '/' )
  744. X                            break;    /* found the end */
  745. X                        }
  746. X
  747. X                    if ( c == EOF )
  748. X                        {
  749. X                        error( "EOF in comment" );
  750. X                        break;
  751. X                        }
  752. X                    }
  753. X                }
  754. X
  755. X.fi
  756. X(Note that if the scanner is compiled using
  757. X.B C++,
  758. Xthen
  759. X.B input()
  760. Xis instead referred to as
  761. X.B yyinput(),
  762. Xin order to avoid a name clash with the
  763. X.B C++
  764. Xstream by the name of
  765. X.I input.)
  766. X.IP -
  767. X.B yyterminate()
  768. Xcan be used in lieu of a return statement in an action.  It terminates
  769. Xthe scanner and returns a 0 to the scanner's caller, indicating "all done".
  770. XSubsequent calls to the scanner will immediately return unless preceded
  771. Xby a call to
  772. X.B yyrestart()
  773. X(see below).
  774. XBy default,
  775. X.B yyterminate()
  776. Xis also called when an end-of-file is encountered.  It is a macro and
  777. Xmay be redefined.
  778. X.SH THE GENERATED SCANNER
  779. XThe output of
  780. X.I flex
  781. Xis the file
  782. X.B lex.yy.c,
  783. Xwhich contains the scanning routine
  784. X.B yylex(),
  785. Xa number of tables used by it for matching tokens, and a number
  786. Xof auxiliary routines and macros.  By default,
  787. X.B yylex()
  788. Xis declared as follows:
  789. X.nf
  790. X
  791. X    int yylex()
  792. X        {
  793. X        ... various definitions and the actions in here ...
  794. X        }
  795. X
  796. X.fi
  797. X(If your environment supports function prototypes, then it will
  798. Xbe "int yylex( void )".)  This definition may be changed by redefining
  799. Xthe "YY_DECL" macro.  For example, you could use:
  800. X.nf
  801. X
  802. X    #undef YY_DECL
  803. X    #define YY_DECL float lexscan( a, b ) float a, b;
  804. X
  805. X.fi
  806. Xto give the scanning routine the name
  807. X.I lexscan,
  808. Xreturning a float, and taking two floats as arguments.  Note that
  809. Xif you give arguments to the scanning routine using a
  810. XK&R-style/non-prototyped function declaration, you must terminate
  811. Xthe definition with a semi-colon (;).
  812. X.LP
  813. XWhenever
  814. X.B yylex()
  815. Xis called, it scans tokens from the global input file
  816. X.I yyin
  817. X(which defaults to stdin).  It continues until it either reaches
  818. Xan end-of-file (at which point it returns the value 0) or
  819. Xone of its actions executes a
  820. X.I return
  821. Xstatement.
  822. XIn the former case, when called again the scanner will immediately
  823. Xreturn unless
  824. X.B yyrestart()
  825. Xis called to point
  826. X.I yyin
  827. Xat the new input file.  (
  828. X.B yyrestart()
  829. Xtakes one argument, a
  830. X.B FILE *
  831. Xpointer.)
  832. XIn the latter case (i.e., when an action
  833. Xexecutes a return), the scanner may then be called again and it
  834. Xwill resume scanning where it left off.
  835. X.LP
  836. XBy default (and for purposes of efficiency), the scanner uses
  837. Xblock-reads rather than simple
  838. X.I getc()
  839. Xcalls to read characters from
  840. X.I yyin.
  841. XThe nature of how it gets its input can be controlled by redefining the
  842. X.B YY_INPUT
  843. Xmacro.
  844. XYY_INPUT's calling sequence is "YY_INPUT(buf,result,max_size)".  Its
  845. Xaction is to place up to
  846. X.I max_size
  847. Xcharacters in the character array
  848. X.I buf
  849. Xand return in the integer variable
  850. X.I result
  851. Xeither the
  852. Xnumber of characters read or the constant YY_NULL (0 on Unix systems)
  853. Xto indicate EOF.  The default YY_INPUT reads from the
  854. Xglobal file-pointer "yyin".
  855. X.LP
  856. XA sample redefinition of YY_INPUT (in the definitions
  857. Xsection of the input file):
  858. X.nf
  859. X
  860. X    %{
  861. X    #undef YY_INPUT
  862. X    #define YY_INPUT(buf,result,max_size) \\
  863. X        { \\
  864. X        int c = getchar(); \\
  865. X        result = (c == EOF) ? YY_NULL : (buf[0] = c, 1); \\
  866. X        }
  867. X    %}
  868. X
  869. X.fi
  870. XThis definition will change the input processing to occur
  871. Xone character at a time.
  872. X.LP
  873. XYou also can add in things like keeping track of the
  874. Xinput line number this way; but don't expect your scanner to
  875. Xgo very fast.
  876. X.LP
  877. XWhen the scanner receives an end-of-file indication from YY_INPUT,
  878. Xit then checks the
  879. X.B yywrap()
  880. Xfunction.  If
  881. X.B yywrap()
  882. Xreturns false (zero), then it is assumed that the
  883. Xfunction has gone ahead and set up
  884. X.I yyin
  885. Xto point to another input file, and scanning continues.  If it returns
  886. Xtrue (non-zero), then the scanner terminates, returning 0 to its
  887. Xcaller.
  888. X.LP
  889. XThe default
  890. X.B yywrap()
  891. Xalways returns 1.  Presently, to redefine it you must first
  892. X"#undef yywrap", as it is currently implemented as a macro.  As indicated
  893. Xby the hedging in the previous sentence, it may be changed to
  894. Xa true function in the near future.
  895. X.LP
  896. XThe scanner writes its
  897. X.B ECHO
  898. Xoutput to the
  899. X.I yyout
  900. Xglobal (default, stdout), which may be redefined by the user simply
  901. Xby assigning it to some other
  902. X.B FILE
  903. Xpointer.
  904. X.SH START CONDITIONS
  905. X.I flex
  906. Xprovides a mechanism for conditionally activating rules.  Any rule
  907. Xwhose pattern is prefixed with "<sc>" will only be active when
  908. Xthe scanner is in the start condition named "sc".  For example,
  909. X.nf
  910. X
  911. X    <STRING>[^"]*        { /* eat up the string body ... */
  912. X                ...
  913. X                }
  914. X
  915. X.fi
  916. Xwill be active only when the scanner is in the "STRING" start
  917. Xcondition, and
  918. X.nf
  919. X
  920. X    <INITIAL,STRING,QUOTE>\\.        { /* handle an escape ... */
  921. X                ...
  922. X                }
  923. X
  924. X.fi
  925. Xwill be active only when the current start condition is
  926. Xeither "INITIAL", "STRING", or "QUOTE".
  927. X.LP
  928. XStart conditions
  929. Xare declared in the definitions (first) section of the input
  930. Xusing unindented lines beginning with either
  931. X.B %s
  932. Xor
  933. X.B %x
  934. Xfollowed by a list of names.
  935. XThe former declares
  936. X.I inclusive
  937. Xstart conditions, the latter
  938. X.I exclusive
  939. Xstart conditions.  A start condition is activated using the
  940. X.B BEGIN
  941. Xaction.  Until the next
  942. X.B BEGIN
  943. Xaction is executed, rules with the given start
  944. Xcondition will be active and
  945. Xrules with other start conditions will be inactive.
  946. XIf the start condition is
  947. X.I inclusive,
  948. Xthen rules with no start conditions at all will also be active.
  949. XIf it is
  950. X.I exclusive,
  951. Xthen
  952. X.I only
  953. Xrules qualified with the start condition will be active.
  954. XA set of rules contingent on the same exclusive start condition
  955. Xdescribe a scanner which is independent of any of the other rules in the
  956. X.I flex
  957. Xinput.  Because of this,
  958. Xexclusive start conditions make it easy to specify "mini-scanners"
  959. Xwhich scan portions of the input that are syntactically different
  960. Xfrom the rest (e.g., comments).
  961. X.LP
  962. XIf the distinction between inclusive and exclusive start conditions
  963. Xis still a little vague, here's a simple example illustrating the
  964. Xconnection between the two.  The set of rules:
  965. X.nf
  966. X
  967. X    %s example
  968. X    %%
  969. X    <example>foo           /* do something */
  970. X
  971. X.fi
  972. Xis equivalent to
  973. X.nf
  974. X
  975. X    %x example
  976. X    %%
  977. X    <INITIAL,example>foo   /* do something */
  978. X
  979. X.fi
  980. X.LP
  981. XThe default rule (to
  982. X.B ECHO
  983. Xany unmatched character) remains active in start conditions.
  984. X.LP
  985. X.B BEGIN(0)
  986. Xreturns to the original state where only the rules with
  987. Xno start conditions are active.  This state can also be
  988. Xreferred to as the start-condition "INITIAL", so
  989. X.B BEGIN(INITIAL)
  990. Xis equivalent to
  991. X.B BEGIN(0).
  992. X(The parentheses around the start condition name are not required but
  993. Xare considered good style.)
  994. X.LP
  995. X.B BEGIN
  996. Xactions can also be given as indented code at the beginning
  997. Xof the rules section.  For example, the following will cause
  998. Xthe scanner to enter the "SPECIAL" start condition whenever
  999. X.I yylex()
  1000. Xis called and the global variable
  1001. X.I enter_special
  1002. Xis true:
  1003. X.nf
  1004. X
  1005. X            int enter_special;
  1006. X
  1007. X    %x SPECIAL
  1008. X    %%
  1009. X            if ( enter_special )
  1010. X                BEGIN(SPECIAL);
  1011. X
  1012. X    <SPECIAL>blahblahblah
  1013. X    ...more rules follow...
  1014. X
  1015. X.fi
  1016. X.LP
  1017. XTo illustrate the uses of start conditions,
  1018. Xhere is a scanner which provides two different interpretations
  1019. Xof a string like "123.456".  By default it will treat it as
  1020. Xas three tokens, the integer "123", a dot ('.'), and the integer "456".
  1021. XBut if the string is preceded earlier in the line by the string
  1022. X"expect-floats"
  1023. Xit will treat it as a single token, the floating-point number
  1024. X123.456:
  1025. X.nf
  1026. X
  1027. X    %{
  1028. X    #include <math.h>
  1029. X    %}
  1030. X    %s expect
  1031. X
  1032. X    %%
  1033. X    expect-floats        BEGIN(expect);
  1034. X
  1035. X    <expect>[0-9]+"."[0-9]+      {
  1036. X                printf( "found a float, = %f\\n",
  1037. X                        atof( yytext ) );
  1038. X                }
  1039. X    <expect>\\n           {
  1040. X                /* that's the end of the line, so
  1041. X                 * we need another "expect-number"
  1042. X                 * before we'll recognize any more
  1043. X                 * numbers
  1044. X                 */
  1045. X                BEGIN(INITIAL);
  1046. X                }
  1047. X
  1048. X    [0-9]+      {
  1049. X                printf( "found an integer, = %d\\n",
  1050. X                        atoi( yytext ) );
  1051. X                }
  1052. X
  1053. X    "."         printf( "found a dot\\n" );
  1054. X
  1055. X.fi
  1056. XHere is a scanner which recognizes (and discards) C comments while
  1057. Xmaintaining a count of the current input line.
  1058. X.nf
  1059. X
  1060. X    %x comment
  1061. X    %%
  1062. X            int line_num = 1;
  1063. X
  1064. X    "/*"         BEGIN(comment);
  1065. X
  1066. X    <comment>[^*\\n]*        /* eat anything that's not a '*' */
  1067. X    <comment>"*"+[^*/\\n]*   /* eat up '*'s not followed by '/'s */
  1068. X    <comment>\\n             ++line_num;
  1069. X    <comment>"*"+"/"        BEGIN(INITIAL);
  1070. X
  1071. X.fi
  1072. XNote that start-conditions names are really integer values and
  1073. Xcan be stored as such.  Thus, the above could be extended in the
  1074. Xfollowing fashion:
  1075. X.nf
  1076. X
  1077. X    %x comment foo
  1078. X    %%
  1079. X            int line_num = 1;
  1080. X            int comment_caller;
  1081. X
  1082. X    "/*"         {
  1083. X                 comment_caller = INITIAL;
  1084. X                 BEGIN(comment);
  1085. X                 }
  1086. X
  1087. X    ...
  1088. X
  1089. X    <foo>"/*"    {
  1090. X                 comment_caller = foo;
  1091. X                 BEGIN(comment);
  1092. X                 }
  1093. X
  1094. X    <comment>[^*\\n]*        /* eat anything that's not a '*' */
  1095. X    <comment>"*"+[^*/\\n]*   /* eat up '*'s not followed by '/'s */
  1096. X    <comment>\\n             ++line_num;
  1097. X    <comment>"*"+"/"        BEGIN(comment_caller);
  1098. X
  1099. X.fi
  1100. XOne can then implement a "stack" of start conditions using an
  1101. Xarray of integers.  (It is likely that such stacks will become
  1102. Xa full-fledged
  1103. X.I flex
  1104. Xfeature in the future.)  Note, though, that
  1105. Xstart conditions do not have their own name-space; %s's and %x's
  1106. Xdeclare names in the same fashion as #define's.
  1107. X.SH MULTIPLE INPUT BUFFERS
  1108. XSome scanners (such as those which support "include" files)
  1109. Xrequire reading from several input streams.  As
  1110. X.I flex
  1111. Xscanners do a large amount of buffering, one cannot control
  1112. Xwhere the next input will be read from by simply writing a
  1113. X.B YY_INPUT
  1114. Xwhich is sensitive to the scanning context.
  1115. X.B YY_INPUT
  1116. Xis only called when the scanner reaches the end of its buffer, which
  1117. Xmay be a long time after scanning a statement such as an "include"
  1118. Xwhich requires switching the input source.
  1119. X.LP
  1120. XTo negotiate these sorts of problems,
  1121. X.I flex
  1122. Xprovides a mechanism for creating and switching between multiple
  1123. Xinput buffers.  An input buffer is created by using:
  1124. X.nf
  1125. X
  1126. X    YY_BUFFER_STATE yy_create_buffer( FILE *file, int size )
  1127. X
  1128. X.fi
  1129. Xwhich takes a
  1130. X.I FILE
  1131. Xpointer and a size and creates a buffer associated with the given
  1132. Xfile and large enough to hold
  1133. X.I size
  1134. Xcharacters (when in doubt, use
  1135. X.B YY_BUF_SIZE
  1136. Xfor the size).  It returns a
  1137. X.B YY_BUFFER_STATE
  1138. Xhandle, which may then be passed to other routines:
  1139. X.nf
  1140. X
  1141. X    void yy_switch_to_buffer( YY_BUFFER_STATE new_buffer )
  1142. X
  1143. X.fi
  1144. Xswitches the scanner's input buffer so subsequent tokens will
  1145. Xcome from
  1146. X.I new_buffer.
  1147. XNote that
  1148. X.B yy_switch_to_buffer()
  1149. Xmay be used by yywrap() to sets things up for continued scanning, instead
  1150. Xof opening a new file and pointing
  1151. X.I yyin
  1152. Xat it.
  1153. X.nf
  1154. X
  1155. X    void yy_delete_buffer( YY_BUFFER_STATE buffer )
  1156. X
  1157. X.fi
  1158. Xis used to reclaim the storage associated with a buffer.
  1159. X.LP
  1160. X.B yy_new_buffer()
  1161. Xis an alias for
  1162. X.B yy_create_buffer(),
  1163. Xprovided for compatibility with the C++ use of
  1164. X.I new
  1165. Xand
  1166. X.I delete
  1167. Xfor creating and destroying dynamic objects.
  1168. X.LP
  1169. XFinally, the
  1170. X.B YY_CURRENT_BUFFER
  1171. Xmacro returns a
  1172. X.B YY_BUFFER_STATE
  1173. Xhandle to the current buffer.
  1174. X.LP
  1175. XHere is an example of using these features for writing a scanner
  1176. Xwhich expands include files (the
  1177. X.B <<EOF>>
  1178. Xfeature is discussed below):
  1179. X.nf
  1180. X
  1181. X    /* the "incl" state is used for picking up the name
  1182. X     * of an include file
  1183. X     */
  1184. X    %x incl
  1185. X
  1186. X    %{
  1187. X    #define MAX_INCLUDE_DEPTH 10
  1188. X    YY_BUFFER_STATE include_stack[MAX_INCLUDE_DEPTH];
  1189. X    int include_stack_ptr = 0;
  1190. X    %}
  1191. X
  1192. X    %%
  1193. X    include             BEGIN(incl);
  1194. X
  1195. X    [a-z]+              ECHO;
  1196. X    [^a-z\\n]*\\n?        ECHO;
  1197. X
  1198. X    <incl>[ \\t]*      /* eat the whitespace */
  1199. X    <incl>[^ \\t\\n]+   { /* got the include file name */
  1200. X            if ( include_stack_ptr >= MAX_INCLUDE_DEPTH )
  1201. X                {
  1202. X                fprintf( stderr, "Includes nested too deeply" );
  1203. X                exit( 1 );
  1204. X                }
  1205. X
  1206. X            include_stack[include_stack_ptr++] =
  1207. X                YY_CURRENT_BUFFER;
  1208. X
  1209. X            yyin = fopen( yytext, "r" );
  1210. X
  1211. X            if ( ! yyin )
  1212. X                error( ... );
  1213. X
  1214. X            yy_switch_to_buffer(
  1215. X                yy_create_buffer( yyin, YY_BUF_SIZE ) );
  1216. X
  1217. X            BEGIN(INITIAL);
  1218. X            }
  1219. X
  1220. X    <<EOF>> {
  1221. X            if ( --include_stack_ptr < 0 )
  1222. X                {
  1223. X                yyterminate();
  1224. X                }
  1225. X
  1226. X            else
  1227. X                yy_switch_to_buffer(
  1228. X                     include_stack[include_stack_ptr] );
  1229. X            }
  1230. X
  1231. X.fi
  1232. X.SH END-OF-FILE RULES
  1233. XThe special rule "<<EOF>>" indicates
  1234. Xactions which are to be taken when an end-of-file is
  1235. Xencountered and yywrap() returns non-zero (i.e., indicates
  1236. Xno further files to process).  The action must finish
  1237. Xby doing one of four things:
  1238. X.IP -
  1239. Xthe special
  1240. X.B YY_NEW_FILE
  1241. Xaction, if
  1242. X.I yyin
  1243. Xhas been pointed at a new file to process;
  1244. X.IP -
  1245. Xa
  1246. X.I return
  1247. Xstatement;
  1248. X.IP -
  1249. Xthe special
  1250. X.B yyterminate()
  1251. Xaction;
  1252. X.IP -
  1253. Xor, switching to a new buffer using
  1254. X.B yy_switch_to_buffer()
  1255. Xas shown in the example above.
  1256. X.LP
  1257. X<<EOF>> rules may not be used with other
  1258. Xpatterns; they may only be qualified with a list of start
  1259. Xconditions.  If an unqualified <<EOF>> rule is given, it
  1260. Xapplies to
  1261. X.I all
  1262. Xstart conditions which do not already have <<EOF>> actions.  To
  1263. Xspecify an <<EOF>> rule for only the initial start condition, use
  1264. X.nf
  1265. X
  1266. X    <INITIAL><<EOF>>
  1267. X
  1268. X.fi
  1269. X.LP
  1270. XThese rules are useful for catching things like unclosed comments.
  1271. XAn example:
  1272. X.nf
  1273. X
  1274. X    %x quote
  1275. X    %%
  1276. X
  1277. X    ...other rules for dealing with quotes...
  1278. X
  1279. X    <quote><<EOF>>   {
  1280. X             error( "unterminated quote" );
  1281. X             yyterminate();
  1282. X             }
  1283. X    <<EOF>>  {
  1284. X             if ( *++filelist )
  1285. X                 {
  1286. X                 yyin = fopen( *filelist, "r" );
  1287. X                 YY_NEW_FILE;
  1288. X                 }
  1289. X             else
  1290. X                yyterminate();
  1291. X             }
  1292. X
  1293. X.fi
  1294. X.SH MISCELLANEOUS MACROS
  1295. XThe macro
  1296. X.bd
  1297. XYY_USER_ACTION
  1298. Xcan be redefined to provide an action
  1299. Xwhich is always executed prior to the matched rule's action.  For example,
  1300. Xit could be #define'd to call a routine to convert yytext to lower-case.
  1301. X.LP
  1302. XThe macro
  1303. X.B YY_USER_INIT
  1304. Xmay be redefined to provide an action which is always executed before
  1305. Xthe first scan (and before the scanner's internal initializations are done).
  1306. XFor example, it could be used to call a routine to read
  1307. Xin a data table or open a logging file.
  1308. X.LP
  1309. XIn the generated scanner, the actions are all gathered in one large
  1310. Xswitch statement and separated using
  1311. X.B YY_BREAK,
  1312. Xwhich may be redefined.  By default, it is simply a "break", to separate
  1313. Xeach rule's action from the following rule's.
  1314. XRedefining
  1315. X.B YY_BREAK
  1316. Xallows, for example, C++ users to
  1317. X#define YY_BREAK to do nothing (while being very careful that every
  1318. Xrule ends with a "break" or a "return"!) to avoid suffering from
  1319. Xunreachable statement warnings where because a rule's action ends with
  1320. X"return", the
  1321. X.B YY_BREAK
  1322. Xis inaccessible.
  1323. X.SH INTERFACING WITH YACC
  1324. XOne of the main uses of
  1325. X.I flex
  1326. Xis as a companion to the
  1327. X.I yacc
  1328. Xparser-generator.
  1329. X.I yacc
  1330. Xparsers expect to call a routine named
  1331. X.B yylex()
  1332. Xto find the next input token.  The routine is supposed to
  1333. Xreturn the type of the next token as well as putting any associated
  1334. Xvalue in the global
  1335. X.B yylval.
  1336. XTo use
  1337. X.I flex
  1338. Xwith
  1339. X.I yacc,
  1340. Xone specifies the
  1341. X.B -d
  1342. Xoption to
  1343. X.I yacc
  1344. Xto instruct it to generate the file
  1345. X.B y.tab.h
  1346. Xcontaining definitions of all the
  1347. X.B %tokens
  1348. Xappearing in the
  1349. X.I yacc
  1350. Xinput.  This file is then included in the
  1351. X.I flex
  1352. Xscanner.  For example, if one of the tokens is "TOK_NUMBER",
  1353. Xpart of the scanner might look like:
  1354. X.nf
  1355. X
  1356. X    %{
  1357. X    #include "y.tab.h"
  1358. X    %}
  1359. X
  1360. X    %%
  1361. X
  1362. X    [0-9]+        yylval = atoi( yytext ); return TOK_NUMBER;
  1363. X
  1364. X.fi
  1365. X.SH TRANSLATION TABLE
  1366. XIn the name of POSIX compliance,
  1367. X.I flex
  1368. Xsupports a
  1369. X.I translation table
  1370. Xfor mapping input characters into groups.
  1371. XThe table is specified in the first section, and its format looks like:
  1372. X.nf
  1373. X
  1374. X    %t
  1375. X    1        abcd
  1376. X    2        ABCDEFGHIJKLMNOPQRSTUVWXYZ
  1377. X    52       0123456789
  1378. X    6        \\t\\ \\n
  1379. X    %t
  1380. X
  1381. X.fi
  1382. XThis example specifies that the characters 'a', 'b', 'c', and 'd'
  1383. Xare to all be lumped into group #1, upper-case letters
  1384. Xin group #2, digits in group #52, tabs, blanks, and newlines into
  1385. Xgroup #6, and
  1386. X.I
  1387. Xno other characters will appear in the patterns.
  1388. XThe group numbers are actually disregarded by
  1389. X.I flex;
  1390. X.B %t
  1391. Xserves, though, to lump characters together.  Given the above
  1392. Xtable, for example, the pattern "a(AA)*5" is equivalent to "d(ZQ)*0".
  1393. XThey both say, "match any character in group #1, followed by
  1394. Xzero-or-more pairs of characters
  1395. Xfrom group #2, followed by a character from group #52."  Thus
  1396. X.B %t
  1397. Xprovides a crude way for introducing equivalence classes into
  1398. Xthe scanner specification.
  1399. X.LP
  1400. XNote that the
  1401. X.B -i
  1402. Xoption (see below) coupled with the equivalence classes which
  1403. X.I flex
  1404. Xautomatically generates take care of virtually all the instances
  1405. Xwhen one might consider using
  1406. X.B %t.
  1407. XBut what the hell, it's there if you want it.
  1408. X.SH OPTIONS
  1409. X.I flex
  1410. Xhas the following options:
  1411. X.TP
  1412. X.B -b
  1413. XGenerate backtracking information to
  1414. X.I lex.backtrack.
  1415. XThis is a list of scanner states which require backtracking
  1416. Xand the input characters on which they do so.  By adding rules one
  1417. Xcan remove backtracking states.  If all backtracking states
  1418. Xare eliminated and
  1419. X.B -f
  1420. Xor
  1421. X.B -F
  1422. Xis used, the generated scanner will run faster (see the
  1423. X.B -p
  1424. Xflag).  Only users who wish to squeeze every last cycle out of their
  1425. Xscanners need worry about this option.  (See the section on PERFORMANCE
  1426. XCONSIDERATIONS below.)
  1427. X.TP
  1428. X.B -c
  1429. Xis a do-nothing, deprecated option included for POSIX compliance.
  1430. X.IP
  1431. X.B NOTE:
  1432. Xin previous releases of
  1433. X.I flex
  1434. X.B -c
  1435. Xspecified table-compression options.  This functionality is
  1436. Xnow given by the
  1437. X.B -C
  1438. Xflag.  To ease the the impact of this change, when
  1439. X.I flex
  1440. Xencounters
  1441. X.B -c,
  1442. Xit currently issues a warning message and assumes that
  1443. X.B -C
  1444. Xwas desired instead.  In the future this "promotion" of
  1445. X.B -c
  1446. Xto
  1447. X.B -C
  1448. Xwill go away in the name of full POSIX compliance (unless
  1449. Xthe POSIX meaning is removed first).
  1450. X.TP
  1451. X.B -d
  1452. Xmakes the generated scanner run in
  1453. X.I debug
  1454. Xmode.  Whenever a pattern is recognized and the global
  1455. X.B yy_flex_debug
  1456. Xis non-zero (which is the default),
  1457. Xthe scanner will write to
  1458. X.I stderr
  1459. Xa line of the form:
  1460. X.nf
  1461. X
  1462. X    --accepting rule at line 53 ("the matched text")
  1463. X
  1464. X.fi
  1465. XThe line number refers to the location of the rule in the file
  1466. Xdefining the scanner (i.e., the file that was fed to flex).  Messages
  1467. Xare also generated when the scanner backtracks, accepts the
  1468. Xdefault rule, reaches the end of its input buffer (or encounters
  1469. Xa NUL; at this point, the two look the same as far as the scanner's concerned),
  1470. Xor reaches an end-of-file.
  1471. X.TP
  1472. X.B -f
  1473. Xspecifies (take your pick)
  1474. X.I full table
  1475. Xor
  1476. X.I fast scanner.
  1477. XNo table compression is done.  The result is large but fast.
  1478. XThis option is equivalent to
  1479. X.B -Cf
  1480. X(see below).
  1481. X.TP
  1482. X.B -i
  1483. Xinstructs
  1484. X.I flex
  1485. Xto generate a
  1486. X.I case-insensitive
  1487. Xscanner.  The case of letters given in the
  1488. X.I flex
  1489. Xinput patterns will
  1490. Xbe ignored, and tokens in the input will be matched regardless of case.  The
  1491. Xmatched text given in
  1492. X.I yytext
  1493. Xwill have the preserved case (i.e., it will not be folded).
  1494. X.TP
  1495. X.B -n
  1496. Xis another do-nothing, deprecated option included only for
  1497. XPOSIX compliance.
  1498. X.TP
  1499. X.B -p
  1500. Xgenerates a performance report to stderr.  The report
  1501. Xconsists of comments regarding features of the
  1502. X.I flex
  1503. Xinput file which will cause a loss of performance in the resulting scanner.
  1504. XNote that the use of
  1505. X.I REJECT
  1506. Xand variable trailing context (see the BUGS section in flex(1))
  1507. Xentails a substantial performance penalty; use of
  1508. X.I yymore(),
  1509. Xthe
  1510. X.B ^
  1511. Xoperator,
  1512. Xand the
  1513. X.B -I
  1514. Xflag entail minor performance penalties.
  1515. X.TP
  1516. X.B -s
  1517. Xcauses the
  1518. X.I default rule
  1519. X(that unmatched scanner input is echoed to
  1520. X.I stdout)
  1521. Xto be suppressed.  If the scanner encounters input that does not
  1522. Xmatch any of its rules, it aborts with an error.  This option is
  1523. Xuseful for finding holes in a scanner's rule set.
  1524. X.TP
  1525. X.B -t
  1526. Xinstructs
  1527. X.I flex
  1528. Xto write the scanner it generates to standard output instead
  1529. Xof
  1530. X.B lex.yy.c.
  1531. X.TP
  1532. X.B -v
  1533. Xspecifies that
  1534. X.I flex
  1535. Xshould write to
  1536. X.I stderr
  1537. Xa summary of statistics regarding the scanner it generates.
  1538. XMost of the statistics are meaningless to the casual
  1539. X.I flex
  1540. Xuser, but the
  1541. Xfirst line identifies the version of
  1542. X.I flex,
  1543. Xwhich is useful for figuring
  1544. Xout where you stand with respect to patches and new releases,
  1545. Xand the next two lines give the date when the scanner was created
  1546. Xand a summary of the flags which were in effect.
  1547. X.TP
  1548. X.B -F
  1549. Xspecifies that the
  1550. X.ul
  1551. Xfast
  1552. Xscanner table representation should be used.  This representation is
  1553. Xabout as fast as the full table representation
  1554. X.ul
  1555. X(-f),
  1556. Xand for some sets of patterns will be considerably smaller (and for
  1557. Xothers, larger).  In general, if the pattern set contains both "keywords"
  1558. Xand a catch-all, "identifier" rule, such as in the set:
  1559. X.nf
  1560. X
  1561. X    "case"    return TOK_CASE;
  1562. X    "switch"  return TOK_SWITCH;
  1563. X    ...
  1564. X    "default" return TOK_DEFAULT;
  1565. X    [a-z]+    return TOK_ID;
  1566. X
  1567. X.fi
  1568. Xthen you're better off using the full table representation.  If only
  1569. Xthe "identifier" rule is present and you then use a hash table or some such
  1570. Xto detect the keywords, you're better off using
  1571. X.ul
  1572. X-F.
  1573. X.IP
  1574. XThis option is equivalent to
  1575. X.B -CF
  1576. X(see below).
  1577. X.TP
  1578. X.B -I
  1579. Xinstructs
  1580. X.I flex
  1581. Xto generate an
  1582. X.I interactive
  1583. Xscanner.  Normally, scanners generated by
  1584. X.I flex
  1585. Xalways look ahead one
  1586. Xcharacter before deciding that a rule has been matched.  At the cost of
  1587. Xsome scanning overhead,
  1588. X.I flex
  1589. Xwill generate a scanner which only looks ahead
  1590. Xwhen needed.  Such scanners are called
  1591. X.I interactive
  1592. Xbecause if you want to write a scanner for an interactive system such as a
  1593. Xcommand shell, you will probably want the user's input to be terminated
  1594. Xwith a newline, and without
  1595. X.B -I
  1596. Xthe user will have to type a character in addition to the newline in order
  1597. Xto have the newline recognized.  This leads to dreadful interactive
  1598. Xperformance.
  1599. X.IP
  1600. XIf all this seems to confusing, here's the general rule: if a human will
  1601. Xbe typing in input to your scanner, use
  1602. X.B -I,
  1603. Xotherwise don't; if you don't care about squeezing the utmost performance
  1604. Xfrom your scanner and you
  1605. Xdon't want to make any assumptions about the input to your scanner,
  1606. Xuse
  1607. X.B -I.
  1608. X.IP
  1609. XNote,
  1610. X.B -I
  1611. Xcannot be used in conjunction with
  1612. X.I full
  1613. Xor
  1614. X.I fast tables,
  1615. Xi.e., the
  1616. X.B -f, -F, -Cf,
  1617. Xor
  1618. X.B -CF
  1619. Xflags.
  1620. X.TP
  1621. X.B -L
  1622. Xinstructs
  1623. X.I flex
  1624. Xnot to generate
  1625. X.B #line
  1626. Xdirectives.  Without this option,
  1627. X.I flex
  1628. Xpeppers the generated scanner
  1629. Xwith #line directives so error messages in the actions will be correctly
  1630. Xlocated with respect to the original
  1631. X.I flex
  1632. Xinput file, and not to
  1633. Xthe fairly meaningless line numbers of
  1634. X.B lex.yy.c.
  1635. X(Unfortunately
  1636. X.I flex
  1637. Xdoes not presently generate the necessary directives
  1638. Xto "retarget" the line numbers for those parts of
  1639. X.B lex.yy.c
  1640. Xwhich it generated.  So if there is an error in the generated code,
  1641. Xa meaningless line number is reported.)
  1642. X.TP
  1643. X.B -T
  1644. Xmakes
  1645. X.I flex
  1646. Xrun in
  1647. X.I trace
  1648. Xmode.  It will generate a lot of messages to
  1649. X.I stdout
  1650. Xconcerning
  1651. Xthe form of the input and the resultant non-deterministic and deterministic
  1652. Xfinite automata.  This option is mostly for use in maintaining
  1653. X.I flex.
  1654. X.TP
  1655. X.B -8
  1656. Xinstructs
  1657. X.I flex
  1658. Xto generate an 8-bit scanner, i.e., one which can recognize 8-bit
  1659. Xcharacters.  On some sites,
  1660. X.I flex
  1661. Xis installed with this option as the default.  On others, the default
  1662. Xis 7-bit characters.  To see which is the case, check the verbose
  1663. X.B (-v)
  1664. Xoutput for "equivalence classes created".  If the denominator of
  1665. Xthe number shown is 128, then by default
  1666. X.I flex
  1667. Xis generating 7-bit characters.  If it is 256, then the default is
  1668. X8-bit characters and the
  1669. X.B -8
  1670. Xflag is not required (but may be a good idea to keep the scanner
  1671. Xspecification portable).  Feeding a 7-bit scanner 8-bit characters
  1672. Xwill result in infinite loops, bus errors, or other such fireworks,
  1673. Xso when in doubt, use the flag.  Note that if equivalence classes
  1674. Xare used, 8-bit scanners take only slightly more table space than
  1675. X7-bit scanners (128 bytes, to be exact); if equivalence classes are
  1676. Xnot used, however, then the tables may grow up to twice their
  1677. X7-bit size.
  1678. X.TP 
  1679. X.B -C[efmF]
  1680. Xcontrols the degree of table compression.
  1681. X.IP
  1682. X.B -Ce
  1683. Xdirects
  1684. X.I flex
  1685. Xto construct
  1686. X.I equivalence classes,
  1687. Xi.e., sets of characters
  1688. Xwhich have identical lexical properties (for example, if the only
  1689. Xappearance of digits in the
  1690. X.I flex
  1691. Xinput is in the character class
  1692. X"[0-9]" then the digits '0', '1', ..., '9' will all be put
  1693. Xin the same equivalence class).  Equivalence classes usually give
  1694. Xdramatic reductions in the final table/object file sizes (typically
  1695. Xa factor of 2-5) and are pretty cheap performance-wise (one array
  1696. Xlook-up per character scanned).
  1697. X.IP
  1698. X.B -Cf
  1699. Xspecifies that the
  1700. X.I full
  1701. Xscanner tables should be generated -
  1702. X.I flex
  1703. Xshould not compress the
  1704. Xtables by taking advantages of similar transition functions for
  1705. Xdifferent states.
  1706. X.IP
  1707. X.B -CF
  1708. Xspecifies that the alternate fast scanner representation (described
  1709. Xabove under the
  1710. X.B -F
  1711. Xflag)
  1712. Xshould be used.
  1713. X.IP
  1714. X.B -Cm
  1715. Xdirects
  1716. X.I flex
  1717. Xto construct
  1718. X.I meta-equivalence classes,
  1719. Xwhich are sets of equivalence classes (or characters, if equivalence
  1720. Xclasses are not being used) that are commonly used together.  Meta-equivalence
  1721. Xclasses are often a big win when using compressed tables, but they
  1722. Xhave a moderate performance impact (one or two "if" tests and one
  1723. Xarray look-up per character scanned).
  1724. X.IP
  1725. XA lone
  1726. X.B -C
  1727. Xspecifies that the scanner tables should be compressed but neither
  1728. Xequivalence classes nor meta-equivalence classes should be used.
  1729. X.IP
  1730. XThe options
  1731. X.B -Cf
  1732. Xor
  1733. X.B -CF
  1734. Xand
  1735. X.B -Cm
  1736. Xdo not make sense together - there is no opportunity for meta-equivalence
  1737. Xclasses if the table is not being compressed.  Otherwise the options
  1738. Xmay be freely mixed.
  1739. X.IP
  1740. XThe default setting is
  1741. X.B -Cem,
  1742. Xwhich specifies that
  1743. X.I flex
  1744. Xshould generate equivalence classes
  1745. Xand meta-equivalence classes.  This setting provides the highest
  1746. Xdegree of table compression.  You can trade off
  1747. Xfaster-executing scanners at the cost of larger tables with
  1748. Xthe following generally being true:
  1749. X.nf
  1750. X
  1751. X    slowest & smallest
  1752. X          -Cem
  1753. X          -Cm
  1754. X          -Ce
  1755. X          -C
  1756. X          -C{f,F}e
  1757. X          -C{f,F}
  1758. X    fastest & largest
  1759. X
  1760. X.fi
  1761. XNote that scanners with the smallest tables are usually generated and
  1762. Xcompiled the quickest, so
  1763. Xduring development you will usually want to use the default, maximal
  1764. Xcompression.
  1765. X.IP
  1766. X.B -Cfe
  1767. Xis often a good compromise between speed and size for production
  1768. Xscanners.
  1769. X.IP
  1770. X.B -C
  1771. Xoptions are not cumulative; whenever the flag is encountered, the
  1772. Xprevious -C settings are forgotten.
  1773. X.TP
  1774. X.B -Sskeleton_file
  1775. Xoverrides the default skeleton file from which
  1776. X.I flex
  1777. Xconstructs its scanners.  You'll never need this option unless you are doing
  1778. X.I flex
  1779. Xmaintenance or development.
  1780. X.SH PERFORMANCE CONSIDERATIONS
  1781. XThe main design goal of
  1782. X.I flex
  1783. Xis that it generate high-performance scanners.  It has been optimized
  1784. Xfor dealing well with large sets of rules.  Aside from the effects
  1785. Xof table compression on scanner speed outlined above,
  1786. Xthere are a number of options/actions which degrade performance.  These
  1787. Xare, from most expensive to least:
  1788. X.nf
  1789. X
  1790. X    REJECT
  1791. X
  1792. X    pattern sets that require backtracking
  1793. X    arbitrary trailing context
  1794. X
  1795. X    '^' beginning-of-line operator
  1796. X    yymore()
  1797. X
  1798. X.fi
  1799. Xwith the first three all being quite expensive and the last two
  1800. Xbeing quite cheap.
  1801. X.LP
  1802. X.B REJECT
  1803. Xshould be avoided at all costs when performance is important.
  1804. XIt is a particularly expensive option.
  1805. X.LP
  1806. XGetting rid of backtracking is messy and often may be an enormous
  1807. Xamount of work for a complicated scanner.  In principal, one begins
  1808. Xby using the
  1809. X.B -b 
  1810. Xflag to generate a
  1811. X.I lex.backtrack
  1812. Xfile.  For example, on the input
  1813. X.nf
  1814. X
  1815. X    %%
  1816. X    foo        return TOK_KEYWORD;
  1817. X    foobar     return TOK_KEYWORD;
  1818. X
  1819. X.fi
  1820. Xthe file looks like:
  1821. X.nf
  1822. X
  1823. X    State #6 is non-accepting -
  1824. X     associated rule line numbers:
  1825. X           2       3
  1826. X     out-transitions: [ o ]
  1827. X     jam-transitions: EOF [ \\001-n  p-\\177 ]
  1828. X
  1829. X    State #8 is non-accepting -
  1830. X     associated rule line numbers:
  1831. X           3
  1832. X     out-transitions: [ a ]
  1833. X     jam-transitions: EOF [ \\001-`  b-\\177 ]
  1834. X
  1835. X    State #9 is non-accepting -
  1836. X     associated rule line numbers:
  1837. X           3
  1838. X     out-transitions: [ r ]
  1839. X     jam-transitions: EOF [ \\001-q  s-\\177 ]
  1840. X
  1841. X    Compressed tables always backtrack.
  1842. X
  1843. X.fi
  1844. XThe first few lines tell us that there's a scanner state in
  1845. Xwhich it can make a transition on an 'o' but not on any other
  1846. Xcharacter, and that in that state the currently scanned text does not match
  1847. Xany rule.  The state occurs when trying to match the rules found
  1848. Xat lines 2 and 3 in the input file.
  1849. XIf the scanner is in that state and then reads
  1850. Xsomething other than an 'o', it will have to backtrack to find
  1851. Xa rule which is matched.  With
  1852. Xa bit of headscratching one can see that this must be the
  1853. Xstate it's in when it has seen "fo".  When this has happened,
  1854. Xif anything other than another 'o' is seen, the scanner will
  1855. Xhave to back up to simply match the 'f' (by the default rule).
  1856. X.LP
  1857. XThe comment regarding State #8 indicates there's a problem
  1858. Xwhen "foob" has been scanned.  Indeed, on any character other
  1859. Xthan a 'b', the scanner will have to back up to accept "foo".
  1860. XSimilarly, the comment for State #9 concerns when "fooba" has
  1861. Xbeen scanned.
  1862. X.LP
  1863. XThe final comment reminds us that there's no point going to
  1864. Xall the trouble of removing backtracking from the rules unless
  1865. Xwe're using
  1866. X.B -f
  1867. Xor
  1868. X.B -F,
  1869. Xsince there's no performance gain doing so with compressed scanners.
  1870. X.LP
  1871. XThe way to remove the backtracking is to add "error" rules:
  1872. X.nf
  1873. X
  1874. X    %%
  1875. X    foo         return TOK_KEYWORD;
  1876. X    foobar      return TOK_KEYWORD;
  1877. X
  1878. X    fooba       |
  1879. X    foob        |
  1880. X    fo          {
  1881. X                /* false alarm, not really a keyword */
  1882. X                return TOK_ID;
  1883. X                }
  1884. X
  1885. X.fi
  1886. X.LP
  1887. XEliminating backtracking among a list of keywords can also be
  1888. Xdone using a "catch-all" rule:
  1889. X.nf
  1890. X
  1891. X    %%
  1892. X    foo         return TOK_KEYWORD;
  1893. X    foobar      return TOK_KEYWORD;
  1894. X
  1895. X    [a-z]+      return TOK_ID;
  1896. X
  1897. X.fi
  1898. XThis is usually the best solution when appropriate.
  1899. X.LP
  1900. XBacktracking messages tend to cascade.
  1901. XWith a complicated set of rules it's not uncommon to get hundreds
  1902. Xof messages.  If one can decipher them, though, it often
  1903. Xonly takes a dozen or so rules to eliminate the backtracking (though
  1904. Xit's easy to make a mistake and have an error rule accidentally match
  1905. Xa valid token.  A possible future
  1906. X.I flex
  1907. Xfeature will be to automatically add rules to eliminate backtracking).
  1908. X.LP
  1909. X.I Variable
  1910. Xtrailing context (where both the leading and trailing parts do not have
  1911. Xa fixed length) entails almost the same performance loss as
  1912. X.I REJECT
  1913. X(i.e., substantial).  So when possible a rule like:
  1914. X.nf
  1915. X
  1916. X    %%
  1917. X    mouse|rat/(cat|dog)   run();
  1918. X
  1919. X.fi
  1920. Xis better written:
  1921. X.nf
  1922. X
  1923. X    %%
  1924. X    mouse/cat|dog         run();
  1925. X    rat/cat|dog           run();
  1926. X
  1927. X.fi
  1928. Xor as
  1929. X.nf
  1930. X
  1931. X    %%
  1932. X    mouse|rat/cat         run();
  1933. X    mouse|rat/dog         run();
  1934. X
  1935. X.fi
  1936. XNote that here the special '|' action does
  1937. X.I not
  1938. Xprovide any savings, and can even make things worse (see
  1939. X.B BUGS
  1940. Xin flex(1)).
  1941. X.LP
  1942. END_OF_FILE
  1943.   if test 49839 -ne `wc -c <'flexdoc.1.01'`; then
  1944.     echo shar: \"'flexdoc.1.01'\" unpacked with wrong size!
  1945.   fi
  1946.   # end of 'flexdoc.1.01'
  1947. fi
  1948. echo shar: End of archive 2 \(of 10\).
  1949. cp /dev/null ark2isdone
  1950. MISSING=""
  1951. for I in 1 2 3 4 5 6 7 8 9 10 ; do
  1952.     if test ! -f ark${I}isdone ; then
  1953.     MISSING="${MISSING} ${I}"
  1954.     fi
  1955. done
  1956. if test "${MISSING}" = "" ; then
  1957.     echo You have unpacked all 10 archives.
  1958.     rm -f ark[1-9]isdone ark[1-9][0-9]isdone
  1959. else
  1960.     echo You still must unpack the following archives:
  1961.     echo "        " ${MISSING}
  1962. fi
  1963. exit 0
  1964. exit 0 # Just in case...
  1965.